﻿using Shake.Framework.Mvc;
using Shake.Framework.Setup;
using Shake.Framework.Utility;
using System;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Shake.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            AutofacConfig.Register();

            //FeatureInitiliazer.Initialize();
            //BuildFrontEntityModelSetup.Initialize();

            // 权限控制
            //var filter = Shake.Framework.Setup.AutofacConfig.Resolve<IShakeAuthorizationFilter>();
            //GlobalFilters.Filters.Add(filter);

            Loop();
        }

        /// <summary>
        /// 辅助
        /// </summary>
        private  static void Loop()
        {
            System.Threading.Tasks.Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        using (var client = new WebClient())
                        {
                            client.DownloadData("http://localhost:8046/");
                        }
                    }
                    catch(Exception ex)
                    {
                        NLogUtil.Error(ex, "loop辅助Error");
                    }
                }
            });
        }


        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            return;
            HttpApplication app = (HttpApplication)sender;
            // TODO:处理日志查看权限问题
            if (Request.Url.ToString().Contains("log.axd"))
            {
                var user = app.Context.User;
                if (user == null)
                {
                    Response.Write("无权限访问");
                    Response.End();
                }
                //var userData = (UserInfo)user;
                ////管理员角色才能查看
                //if (!userData.UserData.IsAdmin)
                //{
                //    Response.Write("无权限访问");
                //    Response.End();
                //}
                //或者指定用户才能访问
                //if (userData.UserData.UserName!="administrator")
                //{
                // Response.Write("无权限访问");
                //Response.End();
                //}
            }
        }
    }
}
